import axios from 'axios'
import { getToken, removeToken } from './auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

// http请求配置

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000 // request timeout
})

// 请求拦截器
axiosInstance.interceptors.request.use(config => {
  // token
  const token = getToken()
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  console.log(error) // for debug
  return Promise.reject(error)
})

// 响应拦截器
axiosInstance.interceptors.response.use(config => {
  const res = config.data
  //debug
  console.log(`[Debug] http response result(${config.config.url}):\n`, res)
  // 非200响应处理
  if (res.code != 200) {
    if (res.code == 401) {
      removeToken()
      // auth error
      router.push('/login')
    }
    else if (res.code == 500) {
      // error
      ElMessage.error(res.message || 'server error')
    }
    return Promise.reject(res.message || 'server error')
  }
  return res
}, error => {
  return Promise.reject(error)
})

export default axiosInstance